#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

struct ListNode {
    int val;
    struct ListNode* next;

};
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    struct ListNode* newhead = NULL;
    struct ListNode* tail = NULL;
    struct ListNode* cur1 = list1;
    struct ListNode* cur2 = list2;
    while (cur1 && cur2)
    {
        if (cur1->val > cur2->val)
        {
            if (newhead == NULL)
            {
                newhead = tail = cur2;
            }
            else
            {
                tail->next = cur2;
                tail = tail->next;
            }
            cur2 = cur2->next;
        }
        else
        {
            if (newhead == NULL)
            {
                newhead = tail = cur1;
            }
            else
            {
                tail->next = cur1;
                tail = tail->next;
            }
            cur1 = cur1->next;
        }
    }
    while (cur1 || cur2)
    {
        if (cur1)
        {
            tail->next = cur1;
            tail = tail->next;
        }
        else
        {
            tail->next = cur2;
            tail = tail->next;
        }
    }
    if (tail)
    {
        tail->next = NULL;
    }
    return newhead;
}
int main()
{
    struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(n1);
    struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(n2);
    struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(n3);
    struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(n4);
    struct ListNode* n5 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(n5);
    struct ListNode* n6 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(n6);

    n1->next = n2;
    n2->next = n3;
    n3->next = NULL;

    n4->next = n5;
    n5->next = n6;
    n6->next = NULL;

    n1->val = 1;
    n2->val = 2;
    n3->val = 4;
    n4->val = 1;
    n5->val = 3;
    n6->val = 4;
}
